package com.jiot.plugin.tio;

import java.io.IOException;

import org.tio.server.ServerTioConfig;
import org.tio.utils.jfinal.P;
import org.tio.websocket.server.WsServerStarter;

import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.IPlugin;


public class TioWebsocketStarterPlugin implements IPlugin{

	private static WsServerStarter wsServerStarter;
	public static ServerTioConfig serverTioConfig;

	
	public TioWebsocketStarterPlugin(String configFile) {
		Prop prop = PropKit.use(configFile);
		
		try {
			wsServerStarter = new WsServerStarter(prop.getInt("tio.serverPort"), MyWsMsgHandler.me);
			serverTioConfig = wsServerStarter.getServerTioConfig();
			serverTioConfig.setName(prop.get("tio.protocolName"));
			serverTioConfig.setServerAioListener(MyServerAioListener.me);
			//设置ip监控
			serverTioConfig.setIpStatListener(MyIpStatListener.me);
			//设置ip统计时间段
			serverTioConfig.ipStats.addDurations(new Long[] { prop.getLong("tio.durations") });
			//设置心跳超时时间
			serverTioConfig.setHeartbeatTimeout(prop.getInt("tio.heartbatTimeout"));
			
			if (prop.getInt("tio.ws.use.ssl", 0) == 1) {
				//如果你希望通过wss来访问，就加上下面的代码吧，不过首先你得有SSL证书（证书必须和域名相匹配，否则可能访问不了ssl）
//				String keyStoreFile = "classpath:config/ssl/keystore.jks";
//				String trustStoreFile = "classpath:config/ssl/keystore.jks";
//				String keyStorePwd = "214323428310224";
				String keyStoreFile = P.get("tio.ssl.keystore", null);
				String trustStoreFile = P.get("tio.ssl.truststore", null);
				String keyStorePwd = P.get("tio.ssl.pwd", null);
				serverTioConfig.useSsl(keyStoreFile, trustStoreFile, keyStorePwd);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	

	@Override
	public boolean start() {
		try {
			wsServerStarter.start();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return true;
	}

	@Override
	public boolean stop() {
		
		return false;
	}

}
